package cn.ml.web1662.reflect;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;

public class Test {
    public static void main(String[] args) throws Exception {

        // cn.ekgc.web1662.reflect.Student
        String className = "cn.ml.web1662.reflect.Student";
        Class clazz = Class.forName(className); //得到类对象
        Student student = null;
        //--------------------------------------------------------------
        student = (Student) clazz.newInstance(); //调用无参构造获得对象
        System.out.println(student);
        System.out.println("调用无参构造对象的姓名："+student.getName());
        //-----------------------------------------------------------------
        Constructor cc = clazz.getConstructor(String.class);
        student = (Student) cc.newInstance("张三");
        System.out.println("通过只有name的有参构造得到对象的对象姓名："+student.getName());

        Constructor[] cs = clazz.getConstructors();//获取所有的构造方法

        for (Constructor c:cs){
            if(c.getParameterCount()==1){ //c的构造方法的个数为1时
                System.out.println("c参数的类型"+c.getParameters()[0].getType());
                System.out.println("c参数名字:"+c.getParameters()[0].getName());
                student = (Student) c.newInstance("abc");
                System.out.println("c的构造方法的个数为1时对象名字："+student.getName());
            }
        }
        System.out.println(clazz.getName());
        System.out.println(clazz.getSimpleName());
        System.out.println(clazz.getModifiers());
        System.out.println("---------------------");
        Field[] fs = clazz.getDeclaredFields();

        for(Field f:fs){
            System.out.println(f);
        }
        fs = clazz.getSuperclass().getDeclaredFields();
        for(Field f:fs){
            System.out.println(f);
        }
        Field f = clazz.getDeclaredField("name");
        f.setAccessible(true);
        f.set(student,"zhangsan");


        Method m = clazz.getDeclaredMethod("setName", String.class);
        m.invoke(student,"李四");
        //System.out.println(student.getName());

        System.out.println(Modifier.toString(clazz.getDeclaredMethod("foo2").getModifiers()));

    }
}
